<template>
  <el-dialog
    v-bind='$attrs'
    :title="$t('cmd.introduction.push_firmware_name')"
    width='500px'
    @open='handleOpen()'
    @close='handleClose'
    @closed='() => (step = 0)'
  >
    <!-- step 1 -->
    <div v-show='step === 0'>
      <div class='flex justify-center cursor-pointer m-auto px-1 py-2 w-pushapp-card'>
        <div class='flex items-center'>
          <img
            src='@/assets/images/logo/ota.png'
            alt
            width='60'
            height='60'
            class='mb-5'
          >
          <div class='float-right'>
            <el-form @submit.prevent.native ref='selectFirm' :model='firmForm' :rules='rules' label-width='100px' size='small'>
              <el-form-item prop='modelCode' :label="$t('device.modelCode')+':'">
                <el-select
                  v-model='firmForm.modelCode'
                  size='mini'
                  :placeholder="$t('device.modelCode')"
                  @change='getFirmVersions'
                >
                  <el-option
                    v-for='devModel in this.deviceModels'
                    :key='devModel.modelCode + devModel.deviceFlag'
                    :label="devModel.modelCode + (devModel.deviceFlag ? ' (' + devModel.deviceFlag + ')' : '')"
                    :value="devModel.modelCode + (devModel.deviceFlag ? '-' + devModel.deviceFlag : '')"
                  />
                </el-select>
              </el-form-item>
              <el-form-item prop='currentVersion' :label="$t('batch.version')+':'">
                <el-select
                  v-model='firmForm.currentVersion'
                  size='mini'
                  :placeholder="$t('batch.version')"
                >
                  <el-option
                    v-for='item in firmVersions'
                    :key='item.appFileId'
                    :label='item.versionName'
                    :value='item.appFileId'
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <!-- step 3 -->
    <div v-show='step === 2'>
      <el-result
        v-if='pushSuccess'
        icon='success'
        :title="$t('batch.push_firm_success')"
      >
      </el-result>
      <el-result
        v-if='!pushSuccess'
        icon='error'
        :title="$t('batch.push_firm_fail')"
      >
      </el-result>
    </div>
    <template #footer></template>
      <span class='dialog-footer'>
        <el-button size='small' @click='handleClose'>{{ step === 0 ? $t('common.cancel') : $t('common.close')}}</el-button>
        <el-button size='small' type='primary' :loading='loading' @click='pushApp' v-show='step === 0'>{{ $t('common.next') }}</el-button>
      </span>
  </el-dialog>
</template>

<script>
import { pushFirm } from '@/api/batch'
import { getModelAndDeviceFlagList } from '@/api/batch'
import { queryVersionList } from '@/api/sysapp'

export default {
  inheritAttrs: false,
  props: { batchId: String },
  data() {
    return {
      step: 0,
      total: 100,
      modelName: '',
      deviceFlag: '',
      modelCode: '',
      manufacturerCode: '',
      deviceModels: [],
      firmVersions: [],
      firmForm: {
        modelCode: '',
        currentVersion: ''
      },
      loading: false,
      pushSuccess: false,
      devSn: '',
      /*rules: {
        modelCode: [
          {
            required: true,
            message: this.$t('batch.please_select_firm_model'),
            trigger: 'blur'
          }
        ],
        currentVersion: [
          {
            required: true,
            message: this.$t('batch.please_select_firm_verison'),
            trigger: 'blur'
          }
        ]
      }*/
    }
  },
  computed: {
    rules() {
      return {
        modelCode: [
          {
            required: true,
            message: this.$t('batch.please_select_firm_model'),
            trigger: 'blur'
          }
        ],
        currentVersion: [
          {
            required: true,
            message: this.$t('batch.please_select_firm_verison'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    devRes(value) {
      if (value) {
        if (value.baseInfo) {
          this.modelName = value.baseInfo.modelName
          this.modelCode = value.baseInfo.modelCode
          this.deviceFlag = value.baseInfo.deviceFlag
          this.manufacturerCode = value.baseInfo.manufacturerCode
        }
        this.devSn = value.deviceBind.devSn
      }
    }
  },
  mounted() {
  },
  methods: {
    handleClose() {
      this.$refs['selectFirm'].resetFields()
      this.$emit('update:model-value', false)
    },
    handleOpen() {
      this.getDeviceModel()
    },
    getDeviceModel() {
      getModelAndDeviceFlagList({}).then((res) => {
        this.deviceModels = res
        if (this.deviceModels.length > 0) {
          this.firmForm.modelCode = this.deviceModels[0].modelCode
          // this.getFirmVersions()
          this.getFirmVersions(this.deviceModels[0].modelCode + (this.deviceModels[0].deviceFlag ? '-' + this.deviceModels[0].deviceFlag : ''))
        }
      })
    },
    getFirmVersions(value) {
      if (value != '') {
        let deviceModel = value.split('-')[0]
        let deviceFlag = value.split('-')[1]
        queryVersionList({
          appTypeCode: '01',
          modelCode: deviceModel,
          deviceFlag: deviceFlag
        }).then((res) => {
          this.firmVersions = res
          this.firmForm.currentVersion = ''
        })
      } else {
        this.firmVersions = []
      }
    },
    pushApp() {
      this.$refs['selectFirm'].validate((valid) => {
        if (valid) {
          let deviceModel
          let deviceFlag
          if (this.firmForm.modelCode != '') {
            deviceModel = this.firmForm.modelCode.split('-')[0]
            deviceFlag = this.firmForm.modelCode.split('-')[1]
          }
          this.loading = true
          pushFirm(this.batchId, this.firmForm.currentVersion,
            { modelCode: deviceModel, deviceFlag: deviceFlag })
            .then(() => {
              this.step = 2
              this.pushSuccess = true
            })
            .catch(() => {
              this.step = 2
              this.pushSuccess = false
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>

<style>
::v-deep .el-dialog .el-dialog__body {
  padding: 0;
}
</style>
